package com.sh1604.duitang.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.sh1604.duitang.R;
import com.sh1604.duitang.fragment.FindFragment;
import com.sh1604.duitang.fragment.HomeFragment;
import com.sh1604.duitang.fragment.MyFragment;
import com.sh1604.duitang.fragment.StoreFragment;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
    private RadioGroup rg_tabs;
    private List<Fragment> mData;
    private int previousIndex;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //控件
        initView();
        //数据源


        initData();

        previousIndex = 0;
        //动态显示需要的碎片，隐藏不需要的
        showFragment(0,previousIndex);
        //监听
        listener();

    }

    private void initView() {
        rg_tabs = (RadioGroup) findViewById(R.id.rg_tabs);
    }

    private void initData() {
        mData = new ArrayList<>();
        HomeFragment fragment1 = new HomeFragment();
        FindFragment fragment2 = new FindFragment();
        StoreFragment fragment3 = new StoreFragment();
        MyFragment fragment4 = new MyFragment();
        mData.add(fragment1);
        mData.add(fragment2);
        mData.add(fragment3);
        mData.add(fragment4);
    }

    private void listener() {
        rg_tabs.setOnCheckedChangeListener(this);
    }



    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        RadioButton rb = (RadioButton) group.findViewById(checkedId);
        int index = group.indexOfChild(rb);
        showFragment(index,previousIndex);
        previousIndex = index;
    }


    public void showFragment(int currentIndex,int previousIndex){
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment showFragment = mData.get(currentIndex);
        Fragment hideFragment = mData.get(previousIndex);
        if (!showFragment.isAdded()){
            ft.add(R.id.fragment,showFragment);
        }
        if (showFragment==hideFragment){
            ft.show(showFragment).commit();
            return;
        }
        ft.show(showFragment).hide(hideFragment).commit();
    }
}

